<template>
	<view class="login-container">
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 短信验证码登录 -->
			<view class="sms-section" v-show="!is_code">
				<view class="form-header">
					<view class="form-title">短信验证码登录</view>
					<view class="form-desc">请输入手机号获取验证码</view>
				</view>
				
				<view class="form-content">
					<view class="input-group">
						<view class="input-label">手机号</view>
						<input 
							type="number" 
							class="form-input" 
							placeholder="请输入11位手机号" 
							v-model="mobile" 
							maxlength="11" 
						/>
					</view>
					
					<view class="input-group">
						<view class="input-label">验证码</view>
						<view class="code-input-wrapper">
							<input 
								type="number" 
								class="form-input code-input" 
								placeholder="请输入6位验证码" 
								v-model="code" 
								maxlength="6" 
							/>
							<view 
								class="code-btn" 
								@click="sendCode" 
								:class="{disabled: countdown > 0}"
							>
								{{ countdown > 0 ? countdown + 's' : '获取验证码' }}
							</view>
						</view>
					</view>
					
					<button class="login-btn" @click="handleSmsLogin">登录</button>
					
					<!-- <view class="back-to-auth" @click="changeiscode(true)">
						<text class="back-text">微信授权登录</text>
					</view> -->
				</view>
			</view>

			<!-- 微信授权登录（隐藏） -->
			<!-- <view class="auth-section" v-show="is_code">
				<view class="auth-card">
					<view class="auth-title">授权登录</view>
					<view class="auth-desc">使用微信授权快速登录</view>
					
					<button 
						class="auth-btn" 
						:class="{disabled: !checked}" 
						@click="checked ? handleWechatAuth() : toast()"
						:disabled="isLoading"
					>
						<view class="btn-content">
							<text class="btn-text">授权手机号登录</text>
						</view>
					</button>
					
					<view class="switch-login" @click="changeiscode(false)">
						<text class="switch-text">短信验证码登录</text>
						<text class="switch-arrow">›</text>
					</view>
				</view>
			</view> -->
		</view>

		<!-- 协议区域 -->
		<view class="agreement-section">
			<view class="agreement-wrapper" @click="changerideo">
				<view class="checkbox" :class="{checked: checked}">
					<text v-if="checked" class="checkmark">✓</text>
				</view>
				<view class="agreement-text">
					<text>阅读并同意</text>
					<text class="link" @click.stop="openshow(1)">《用户协议》</text>
					<text>与</text>
					<text class="link" @click.stop="openshow(2)">《平台协议》</text>
				</view>
			</view>
		</view>

		<!-- 协议弹窗 -->
		<tm-overlay v-model:show="showWin" contentAnimation>
			<view class="protocol-modal">
				<view class="modal-header">
					<text class="modal-title">{{ pop_type == 1 ? '用户协议' : '平台协议' }}</text>
					<view class="close-btn" @click="showWin = false">×</view>
				</view>
				<view class="modal-content">
					<tm-html :content="pop_type == 1 ? user_protocol : privacy_protocol"></tm-html>
				</view>
			</view>
		</tm-overlay>
	</view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app';
import {wxMobile,wxAuth,getParams,sendSmsCode,smsLogin,h5Auth,inviteLinkageUser} from '@/utils/api'
import { ref } from 'vue';

onLoad(async (options: any)=>{
	// 处理hash模式下的参数获取
	let urlPid = options.pid;
	
	// 如果options中没有pid，尝试从URL中获取
	if (!urlPid) {
		// 方法1：从hash中获取参数
		if (window.location.hash && window.location.hash.includes('?')) {
			const hashParams = new URLSearchParams(window.location.hash.split('?')[1]);
			urlPid = hashParams.get('pid');
		}
		
		// 方法2：从search中获取参数
		if (!urlPid) {
			const urlParams = new URLSearchParams(window.location.search);
			urlPid = urlParams.get('pid');
		}
		
		// 方法3：手动解析hash
		if (!urlPid && window.location.hash) {
			const hash = window.location.hash;
			const pidMatch = hash.match(/[?&]pid=([^&]+)/);
			if (pidMatch) {
				urlPid = decodeURIComponent(pidMatch[1]);
			}
		}
	}
	
	if(urlPid){
		pid.value = urlPid;
		console.log('H5登录页面获取到pid:', urlPid);
		// 保存到本地存储
		uni.setStorageSync('pid', urlPid);
	}
	
	// 获取微信配置
	try {
		await fetchWechatConfig();
	} catch (error) {
		console.error('初始化微信配置失败:', error);
		uni.showToast({
			title: '系统配置错误，请联系管理员',
			icon: 'none',
			duration: 3000
		});
	}
	
	_protocol()
})

const pid=ref('')
const showWin = ref(false)
const is_code = ref(false) // false显示短信登录，true显示微信授权
const mobile = ref('')
const code = ref('')
const countdown = ref(0)
const checked = ref(false)//是否同意协议
const isLoading = ref(false)
const user_protocol = ref()//用户协议
const privacy_protocol = ref()//平台协议

// 获取协议内容
const _protocol =() =>{
	getParams({fields:['privacy_policy','platform_protocol']}).then(res=>{
		if(res.code==1){
			user_protocol.value = res.data.privacy_policy
			privacy_protocol.value = res.data.platform_protocol
		}
	})
}

const changerideo =() =>{
	checked.value = !checked.value
}

const pop_type = ref()
const openshow =(type:number) =>{
	pop_type.value = type
	showWin.value = true
}

// 切换登录方式
const changeiscode = (show: boolean) => {
	console.log('切换登录方式:', show ? '短信登录' : '微信登录')
	is_code.value = show
	if (!show) {
		// 重置表单
		mobile.value = ''
		code.value = ''
		countdown.value = 0
	}
}

// 协议提示
const toast = () =>{
	if(!checked.value){
			uni.showToast({
				title:'请阅读并同意相关协议',
				icon:'none'
			})
			return
		}
}

// 返回上一页
const goBack = () => {
	uni.navigateBack({
		delta: 1
	})
}

// 发送短信验证码
const sendCode = () => {
	if (countdown.value > 0) return
	
	if (!mobile.value) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		})
		return
	}
	
	if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		})
		return
	}
	
	sendSmsCode({ mobile: mobile.value }).then(res => {
		if (res.code === 1) {
			uni.showToast({
				title: '验证码已发送',
				icon: 'success'
			})
			// 开发环境提示固定验证码
			// #ifdef H5
			// if (process.env.NODE_ENV === 'development') {
			// 	setTimeout(() => {
			// 		uni.showModal({
			// 			title: '开发环境提示',
			// 			content: '验证码：123456（开发环境固定验证码）',
			// 			showCancel: false
			// 		})
			// 	}, 1000)
			// }
			// #endif
			// 开始倒计时
			countdown.value = 60
			const timer = setInterval(() => {
				countdown.value--
				if (countdown.value <= 0) {
					clearInterval(timer)
				}
			}, 1000)
		} else {
			uni.showToast({
				title: res.msg || '发送失败',
				icon: 'none'
			})
		}
	}).catch(err => {
		uni.showToast({
			title: '发送失败',
			icon: 'none'
		})
	})
}

// 短信验证码登录
const handleSmsLogin = () => {
	// 检查协议勾选状态
	console.log('协议勾选状态:', checked.value)
	if (!checked.value) {
		uni.showToast({
			title: '请阅读并同意相关协议',
			icon: 'none'
		})
		return
	}
	
	if (!mobile.value) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		})
		return
	}
	
	if (!code.value) {
		uni.showToast({
			title: '请输入验证码',
			icon: 'none'
		})
		return
	}
	
	if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		})
		return
	}
	
	// 判断来源页面，传递相应的参数
	const from = pid.value ? 'invite' : 'login';
	
	smsLogin({ 
		mobile: mobile.value, 
		code: code.value,
		parent_id: pid.value || uni.getStorageSync('pid') || '',
		from: from,
		pid: pid.value || 0
	}).then(res => {
		if (res.code === 1) {
		// 检查是否需要绑定微信
		if (res.data.need_bind_wechat) {
			console.log('用户需要绑定微信号');
			// 必须绑定微信，直接跳转到微信授权页面
			handleWechatBind(res.data.id);
		} else {
			// 不需要绑定微信，直接继续登录流程
			proceedWithLogin(res.data);
		}
		} else {
			uni.showToast({
				title: res.msg || '登录失败',
				icon: 'none'
			})
		}
	}).catch(err => {
		uni.showToast({
			title: '登录失败',
			icon: 'none'
		})
	})
}

// 检查URL参数
const checkUrlParams = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const login = urlParams.get('login');
  const token = urlParams.get('token');
  const user_id = urlParams.get('user_id');
  const openid = urlParams.get('openid');
  
  if (login === 'success' && token) {
    saveLoginInfo(token, user_id || '', openid || '');
  }
}

// 保存登录信息
const saveLoginInfo = (token: string, user_id: string, openid: string) => {
  try {
    const loginData = {
      token: token,
      user_id: user_id || '',
      openid: openid || '',
      login_time: Date.now()
    };
    
    localStorage.setItem('h5_login_data', JSON.stringify(loginData));
    uni.setStorageSync('h5_login_data', JSON.stringify(loginData));
    uni.setStorageSync('h5_token', token);
    uni.setStorageSync('h5_user_info', JSON.stringify({
      id: user_id,
      openid: openid,
      nickname: '',
      avatar: '',
      mobile: '',
      token: token
    }));
    
    uni.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 1500
    });
    
    // 如果有邀请码，绑定邀请关系
    // 如果pid.value为空，尝试从本地存储恢复
    if (!pid.value) {
      const storedPid = uni.getStorageSync('pid');
      if (storedPid) {
        pid.value = storedPid;
        console.log('从本地存储恢复pid:', storedPid);
      }
    }
    
    if (pid.value && user_id) {
      console.log('准备绑定邀请关系:', {pid: pid.value, user_id: user_id});
      bindInviteRelation(parseInt(user_id));
    } else {
      console.log('跳过绑定邀请关系:', {pid: pid.value, user_id: user_id});
    }
    
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/index/index'
      });
    }, 2000);
    
  } catch (error) {
    console.error('保存登录信息失败:', error);
    uni.showToast({
      title: '保存登录信息失败',
      icon: 'none'
    });
  }
}

// 绑定邀请关系（只在有邀请码时执行）
const bindInviteRelation = async (newUserId: number) => {
  // 只有在有邀请码的情况下才进行绑定
  if (!pid.value) {
    console.log('没有邀请码，跳过绑定');
    return;
  }
  
  try {
    console.log('开始绑定邀请关系:', {
      inviter_id: parseInt(pid.value),
      new_user_id: newUserId
    });
    
    const res = await inviteLinkageUser({
      inviter_id: parseInt(pid.value),
      new_user_id: newUserId
    });
    
    if (res.code === 1) {
      console.log('邀请关系绑定成功');
      uni.showToast({
        title: '邀请关系绑定成功',
        icon: 'success'
      });
    } else {
      console.warn('邀请关系绑定失败:', res.msg);
      // 绑定失败不影响登录流程，只记录日志
    }
  } catch (error) {
    console.error('绑定邀请关系失败:', error);
    // 绑定失败不影响登录流程，只记录日志
  }
}

// 微信授权登录
const handleWechatAuth = async () => {
	if (!checked.value) {
		uni.showToast({
			title: '请阅读并同意相关协议',
			icon: 'none'
		})
		return
	}
	
	isLoading.value = true
	
	try {
		const isWechat = uni.getSystemInfoSync().platform === 'devtools' || 
						 /micromessenger/i.test(navigator.userAgent)
		
		if (isWechat) {
			await directWechatAuth()
		} else {
			uni.showToast({
				title: '请在微信中打开此页面',
				icon: 'none'
			})
		}
	} catch (error) {
		uni.showToast({
			title: '授权失败，请重试',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

// 直接微信授权
const directWechatAuth = async () => {
  try {
    // 判断来源页面，传递相应的参数
    const from = pid.value ? 'invite' : 'login';
    const res = await h5Auth({
      from: from,
      pid: pid.value || 0
    })
    
    if (res.code === 30) {
      const authUrl = res.data.auth_url
      window.location.href = authUrl
    } else if (res.code === 1) {
      userInfo.value = res.data
      isLoggedIn.value = true
      uni.setStorageSync('h5_token', res.data.token)
      uni.setStorageSync('h5_user_info', JSON.stringify(res.data))
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
    } else if (res.code === 22) {
      userInfo.value = res.data
      isLoggedIn.value = true
      uni.setStorageSync('h5_token', res.data.token)
      uni.setStorageSync('h5_user_info', JSON.stringify(res.data))
      
      uni.showToast({
        title: '登录成功，请绑定手机号',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: res.msg || '授权失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '授权失败，请重试',
      icon: 'none'
    })
  }
}

// 继续登录流程（不需要绑定微信或用户选择稍后绑定）
const proceedWithLogin = (loginData: any) => {
	// 保存H5登录数据
	const h5LoginData = {
		token: loginData.token,
		user_id: loginData.id,
		openid: loginData.openid || '',
		login_time: Date.now()
	};
	
	uni.setStorageSync('h5_login_data', JSON.stringify(h5LoginData));
	uni.setStorageSync('h5_token', loginData.token);
	uni.setStorageSync('token', loginData.token);
	uni.setStorageSync('id', loginData.id);
	
	uni.showToast({
		title: '登录成功',
		icon: 'success'
	})
	
	// 根据后端返回的跳转信息决定跳转目标
	if (loginData.redirect_info) {
		const redirectInfo = loginData.redirect_info;
		console.log('收到跳转信息:', redirectInfo);
		
		if (redirectInfo.redirect_type === 'invite') {
			// 从邀请页面来的，直接跳转到邀请页面并自动绑定
			setTimeout(() => {
				// 使用后端返回的完整URL，但转换为相对路径
				// 动态获取当前域名，替换为相对路径
				const currentDomain = window.location.origin;
				const url = redirectInfo.redirect_url.replace(`${currentDomain}/h5/#/`, '');
				uni.reLaunch({
					url: `/${url}`
				});
			}, 1500);
		} else {
			// 其他情况跳转到首页
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				});
			}, 1500);
		}
	} else {
		// 兼容旧版本，使用原有逻辑
		if (pid.value) {
			bindInviteRelation(loginData.id);
		}
		
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/index/index'
			});
		}, 1500);
	}
}

// 处理微信绑定
const handleWechatBind = (userId = null) => {
	// 检查是否在微信环境中
	const isWechat = uni.getSystemInfoSync().platform === 'devtools' || 
					 /micromessenger/i.test(navigator.userAgent)
	
	if (isWechat) {
		// 在微信环境中，直接进行微信授权绑定
		directWechatBind(userId);
	} else {
		uni.showToast({
			title: '请在微信中打开此页面进行绑定',
			icon: 'none'
		})
	}
}

// 直接微信授权绑定
const directWechatBind = async (userId = null) => {
	try {
		// 获取用户ID，优先使用传入的userId，否则从存储中获取
		const currentUserId = userId || uni.getStorageSync('id');
		console.log('绑定微信使用的用户ID:', currentUserId);
		
		// 构建state参数，需要base64编码
		const stateData = {
			action: 'bind',
			user_id: currentUserId,
			from: 'login',
			pid: 0
		};
		const state = btoa(JSON.stringify(stateData));
		
		// 获取微信授权码
		const appId = getAppId();
		const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(window.location.origin + '/api/login/h5AuthSuccess')}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
		
		console.log('微信绑定授权URL:', authUrl);
		window.location.href = authUrl;
	} catch (error) {
		console.error('微信绑定失败:', error);
		uni.showToast({
			title: error.message || '绑定失败，请重试',
			icon: 'none'
		})
	}
}

// 微信AppID配置
let wechatAppId = ''; // 只能通过配置获取

// 获取微信AppID
const getAppId = () => {
	if (!wechatAppId) {
		throw new Error('微信AppID未配置，请检查系统配置');
	}
	return wechatAppId;
}

// 从系统配置获取微信AppID
const fetchWechatConfig = async () => {
	try {
		const res = await getParams({
			fields: ['appid']
		});
		
		if (res.code === 1 && res.data && res.data.appid) {
			wechatAppId = res.data.appid;
			console.log('从系统配置获取到微信AppID:', wechatAppId);
			return wechatAppId;
		} else {
			throw new Error('系统配置中未找到appid配置');
		}
	} catch (error) {
		console.error('获取微信配置失败:', error);
		throw new Error('获取微信配置失败: ' + error.message);
	}
}

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('h5_token')
        uni.removeStorageSync('h5_user_info')
        uni.removeStorageSync('h5_login_data')
        
        isLoggedIn.value = false
        userInfo.value = {
          id: '',
          openid: '',
          nickname: '',
          avatar: '',
          mobile: '',
          token: ''
        }
        
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
      }
    }
  })
}
</script>

<style lang="scss">
@import 'h5login.scss';
</style>
